﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GoodMan.Infrastructure.Entities.Repository
{
    [Table("T_Duty")]
    public class T_Duty : IEntity<T_Duty>
    {
        [Key]
        [Column(TypeName="int")]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        /// <summary>
        /// yyyy-MM-dd
        /// </summary>
        [Column(TypeName = "varchar")]
        [StringLength(128)]
        public string Date { get; set; }

        [Column(TypeName="text")]
        public string Content { get; set; }
        public DateTime RecordDate { get; set; }

        [Column(TypeName="varchar")]
        [StringLength(128)]
        public string Creator { get; set; }

        public override T_Duty Find(string key)
        {
            int id = Int32.Parse(key);
            return Find(c => c.Id == id);
        }

        public override T_Duty Find(System.Linq.Expressions.Expression<Func<T_Duty, bool>> where)
        {
            using(Context ctx = new Context())
            {
                var item = ctx.Duty.FirstOrDefault(where);
                if (item != null)
                {
                    this.Content = item.Content;
                    this.Creator = item.Creator;
                    this.Date = item.Date;
                    this.Id = item.Id;
                    this.RecordDate = item.RecordDate;
                    return this;
                }
                return null;
            }
        }

        public override bool Any(System.Linq.Expressions.Expression<Func<T_Duty, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Duty.Any(where);
            }
        }

        public override T_Duty FindLast(System.Linq.Expressions.Expression<Func<T_Duty, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.Duty.OrderByDescending(c=>c.Id).FirstOrDefault(where);
                if (item != null)
                {
                    this.Content = item.Content;
                    this.Creator = item.Creator;
                    this.Date = item.Date;
                    this.Id = item.Id;
                    this.RecordDate = item.RecordDate;
                    return this;
                }
                return null;
            }
        }
    }
}
